package com.uzai.console.service.alarm.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.IdentityEnum;
import com.uzai.common.enums.TakeBalStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.Math;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.alarm.alarmriskuser.AlarmRiskUserIdDto;
import com.uzai.console.dto.alarm.alarmriskuser.AlarmRiskUserQuery;
import com.uzai.console.dto.alarm.alarmriskuser.AlarmRiskUserStatusUpdateDto;
import com.uzai.console.dto.feign.userextinfo.UserExtInfoQueryDto;
import com.uzai.console.dto.feign.uzaimanage.SysRunlogWarningDto;
import com.uzai.console.dto.takebal.usertakebal.UserTakeBalQuery;
import com.uzai.console.entity.AlarmRiskUser;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.TakeBalBlacklist;
import com.uzai.console.entity.UserType;
import com.uzai.console.entity.es.EsUserExtInfo;
import com.uzai.console.mapper.AlarmRiskUserMapper;
import com.uzai.console.mapper.TakeBalBlacklistMapper;
import com.uzai.console.mapper.UserTakeBalMapper;
import com.uzai.console.mapper.UserTypeMapper;
import com.uzai.console.service.alarm.AlarmRiskUserService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UserExtInfoFeignService;
import com.uzai.console.service.feign.UzaiManageFeignService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.alarm.alramriskuser.AlarmRiskUserVo;
import com.uzai.console.vo.takebal.takebalblacklist.TakeBalBlacklistInfoVo;
import com.uzai.console.vo.takebal.usertakebal.UserTakeBalReportVo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 风险监控报警用户
 *
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class AlarmRiskUserServiceImpl implements AlarmRiskUserService {

    Logger logger = LoggerFactory.getLogger(AlarmRiskUserServiceImpl.class);

    @Autowired
    private AlarmRiskUserMapper alarmRiskUserMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UserTakeBalMapper userTakeBalMapper;
    @Autowired
    private UserExtInfoFeignService userExtInfoFeignService;
    @Autowired
    private UzaiManageFeignService uzaiManageFeignService;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private TakeBalBlacklistMapper takeBalBlacklistMapper;

    /**
     * 查询风险监控报警用户列表
     *
     * @param alarmRiskUserQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<AlarmRiskUserVo> findAlarmRiskUserByPage(AlarmRiskUserQuery alarmRiskUserQuery) {
        //新建返回到页面的LIST对象
        List<AlarmRiskUserVo> alarmRiskUserPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<AlarmRiskUser> page = new Page<>();
        alarmRiskUserQuery.convert(page);
        ArrayList<AlarmRiskUser> alarmRiskUserList = alarmRiskUserMapper.findByList(page, alarmRiskUserQuery);
        if (alarmRiskUserList != null && alarmRiskUserList.size() > 0) {
            for (AlarmRiskUser alarmRiskUser : alarmRiskUserList) {
                AlarmRiskUserVo alarmRiskUserVo = new AlarmRiskUserVo();
                BeanUtils.copyProperties(alarmRiskUser, alarmRiskUserVo);
                //封装会员信息列表
                if (alarmRiskUser.getUserId() != null) {
                    User user = userService.findUserInfo(alarmRiskUser.getUserId(), alarmRiskUser.getDeviceType(), alarmRiskUser.getMerId());
                    if (user != null) {
                        alarmRiskUserVo.setUserName(user.getNickName());
                        alarmRiskUserVo.setUserRemark(user.getRemark());
                    }
                }
                //封装机器人
                if (alarmRiskUser.getDeviceUniqueId() != null) {
                    Device device = deviceService.findDeviceInfoByDeviceUniqueId(alarmRiskUser.getDeviceUniqueId(), alarmRiskUser.getDeviceType(), alarmRiskUser.getMerId());
                    if (device != null) {
                        alarmRiskUserVo.setDeviceId(device.getDeviceId());
                        alarmRiskUserVo.setDeviceName(device.getDeviceName());
                        alarmRiskUserVo.setDeviceRemark(device.getDeviceRemark());
                    }
                }
                alarmRiskUserPageVoList.add(alarmRiskUserVo);
            }
        }

        //返回到页面分页对象
        Page<AlarmRiskUserVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(alarmRiskUserPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询风险监控报警用户详情
     *
     * @param alarmRiskUserIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public AlarmRiskUserVo findAlarmRiskUserById(AlarmRiskUserIdDto alarmRiskUserIdDto) {
        if (alarmRiskUserIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        AlarmRiskUser alarmRiskUser = alarmRiskUserMapper.selectById(alarmRiskUserIdDto.getId(), alarmRiskUserIdDto.getMerId());

        if (alarmRiskUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该风险监控报警用户不存在");
        }

        AlarmRiskUserVo alarmRiskUserVo = new AlarmRiskUserVo();
        BeanUtils.copyProperties(alarmRiskUser, alarmRiskUserVo);

        //封装会员信息列表
        if (alarmRiskUser.getUserId() != null) {
            User user = userService.findUserInfo(alarmRiskUser.getUserId(), alarmRiskUser.getDeviceType(), alarmRiskUser.getMerId());
            if (user != null) {
                alarmRiskUserVo.setUserName(user.getNickName());
                alarmRiskUserVo.setUserRemark(user.getRemark());
                alarmRiskUserVo.setIdentity(user.getIdentity());
                alarmRiskUserVo.setIdentityName(IdentityEnum.getById(user.getIdentity()).getDesc());
                alarmRiskUserVo.setBalance(Tools.getDouble(user.getBalance()));
                alarmRiskUserVo.setIntegral(Tools.getInteger(user.getIntegral()));
                alarmRiskUserVo.setUserRegTime(user.getRegTime());
                alarmRiskUserVo.setUserType(user.getUserType());
                if(user.getUserType() != null){
                    UserType userType = userTypeMapper.selectById(user.getUserType(), user.getMerId());
                    if(userType != null){
                        alarmRiskUserVo.setUserTypeName(userType.getName());
                    }
                }
            }

            //查询有效订单笔数
            if(StringUtils.isNotBlank(alarmRiskUser.getDeviceType())){
                UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                userExtInfoQueryDto.setMerId(alarmRiskUser.getMerId());
                DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(alarmRiskUser.getDeviceType());
                if(deviceTypeEnum != null){
                    userExtInfoQueryDto.setDeviceType(deviceTypeEnum.getId());
                }
                userExtInfoQueryDto.setBizUserId(user.getBizUserId());
                List<String> keys = new ArrayList<>();
                keys.add("ValidOrderCount"); //首字母大写
                userExtInfoQueryDto.setKeys(keys);

                //查询用户额外信息
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();

                UzaiRespVo<EsUserExtInfo> uzaiRespVo =  userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);

                stopWatch.stop();
                //logger.info("-获取提现总金额接口分析：" + stopWatch.prettyPrint());
                //超过10秒的事务，报警
                if(stopWatch.getTotalTimeSeconds() > 10){
                    SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                    sysRunlogWarningDto.setText("风险监控报警查询会员订单总量，超过10秒的请求监控！\n类名：UserTakeBalServiceImpl"+"\n方法：findUserTakeBalInfo"+"\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
                    UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                    logger.info("--调用官方钉钉报警超过10秒未处理完成的风险监控报警查询会员订单总量接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                }

                logger.info("----提现风险监控报警会员订单总量----uzaiRespVo="+JSONObject.toJSONString(uzaiRespVo));
                if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                    EsUserExtInfo esUserExtInfo = uzaiRespVo.getData();
                    if(esUserExtInfo != null){
                        alarmRiskUserVo.setOrderCount(esUserExtInfo.getValidOrderCount());
                    }
                }
            }

            //提现总数
            UserTakeBalQuery userTakeBalQueryUser = new UserTakeBalQuery();
            userTakeBalQueryUser.setMerId(alarmRiskUser.getMerId());
            userTakeBalQueryUser.setUserId(alarmRiskUser.getUserId());
            UserTakeBalReportVo userTakeBalReportVo = userTakeBalMapper.selectUserTakeBalReport(userTakeBalQueryUser);
            if(userTakeBalReportVo != null){
                alarmRiskUserVo.setTakeBalCount(Tools.getInteger(userTakeBalReportVo.getTakeBalCount()));
            }

            //30天成功提现统计
            UserTakeBalQuery userTakeBalQueryUser_byDays = new UserTakeBalQuery();
            userTakeBalQueryUser_byDays.setMerId(alarmRiskUser.getMerId());
            userTakeBalQueryUser_byDays.setUserId(alarmRiskUser.getUserId());
            int now = DateUtil.getNowTime();
            Integer queryEndTime = now;
            //30天之前的时间
            Integer queryStartTime = queryEndTime - 30 * 24 * 3600;
            userTakeBalQueryUser_byDays.setQueryStartTime(queryStartTime);
            userTakeBalQueryUser_byDays.setQueryEndTime(queryEndTime);
            //自动提现成功和手动审核成功
            userTakeBalQueryUser_byDays.setStatusList(Arrays.asList(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_SUCCESS.getValue(), TakeBalStatusEnum.TBS_MANUAL_AUDIT_SUCCESS.getValue()));
            UserTakeBalReportVo userTakeBalReportVo_byDays = userTakeBalMapper.selectUserTakeBalReport(userTakeBalQueryUser_byDays);
            if(userTakeBalReportVo_byDays != null){
                alarmRiskUserVo.setUserTakeBalCountByDays(Tools.getInteger(userTakeBalReportVo_byDays.getTakeBalCount()));
                //提现总金额=总提现金额+奖励金额
                Double userTakeBalAmountByDays = Math.add(Tools.getDouble(userTakeBalReportVo_byDays.getTakeBalTotal()), Tools.getDouble(userTakeBalReportVo_byDays.getTakeRewardBalTotal()));
                alarmRiskUserVo.setUserTakeBalAmountByDays(userTakeBalAmountByDays);
            }

            //是否是提现黑名单
            TakeBalBlacklist takeBalBlacklist = takeBalBlacklistMapper.selectByUserId(alarmRiskUser.getUserId(), alarmRiskUser.getMerId());
            if(takeBalBlacklist != null){
                TakeBalBlacklistInfoVo takeBalBlacklistInfoVo = new TakeBalBlacklistInfoVo();
                BeanUtils.copyProperties(takeBalBlacklist, takeBalBlacklistInfoVo);
                alarmRiskUserVo.setTakeBalBlacklistInfoVo(takeBalBlacklistInfoVo);
            }
        }

        //封装机器人
        if (alarmRiskUser.getDeviceUniqueId() != null) {
            Device device = deviceService.findDeviceInfoByDeviceUniqueId(alarmRiskUser.getDeviceUniqueId(), alarmRiskUser.getDeviceType(), alarmRiskUser.getMerId());
            if (device != null) {
                alarmRiskUserVo.setDeviceId(device.getDeviceId());
                alarmRiskUserVo.setDeviceName(device.getDeviceName());
                alarmRiskUserVo.setDeviceRemark(device.getDeviceRemark());
            }
        }

        return alarmRiskUserVo;
    }


    /**
     * 修改风险监控报警用户状态
     *
     * @param alarmRiskUserStatusUpdateDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updateAlarmRiskUserStatus(AlarmRiskUserStatusUpdateDto alarmRiskUserStatusUpdateDto){
        if (alarmRiskUserStatusUpdateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if (alarmRiskUserStatusUpdateDto.getStatus() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入状态");
        }

        AlarmRiskUser alarmRiskUser = alarmRiskUserMapper.selectById(alarmRiskUserStatusUpdateDto.getId(), alarmRiskUserStatusUpdateDto.getMerId());
        if (alarmRiskUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该风险监控报警用户不存在");
        }

        alarmRiskUser.setStatus(alarmRiskUserStatusUpdateDto.getStatus());
        alarmRiskUser.setUpdateTime(DateUtil.getNowTime());
        alarmRiskUserMapper.updateById(alarmRiskUser);

    }

}
